package qsc.algorithm.KMP;

import java.util.Arrays;

/**
 * @auther QiuShangcheng
 * @create 2021/5/1
 */
public class Review {

    public static void main(String[] args) {
        String str1 = "BBC ABCDAB ABCDABCDABDE";
        String str2 = "ABCDABD";
        int[] next = Review.kmpNext("ABCDABD");
        System.out.println("next=" + Arrays.toString(next));
        System.out.println("index:" + Review.kmpReview(str1, str2, next));

    }

    /**
     * 核心就在于dest.charAt(i) != dest.charAt(j)，j回溯；dest.charAt(i) == dest.charAt(j)，j++这两种情况
     *
     * @param dest
     * @return
     */
    public static int[] kmpNext(String dest) {
        int[] next = new int[dest.length()];
        next[0] = 0;
        for (int i = 1, j = 0; i < dest.length(); i++) {
            while (j > 0 && dest.charAt(i) != dest.charAt(j)) {
                j = next[j - 1];
            }
            if (dest.charAt(i) == dest.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }



    public static int kmpReview(String str1, String str2, int[] next) {
        for (int i = 0, j = 0; i < str1.length(); i++) {
            while (j > 0 && str1.charAt(i) != str2.charAt(j)) {
                j = next[j - 1];
            }
            if (str1.charAt(i) == str2.charAt(j)) {
                j++;
            }
            if (j == str2.length()) {
                return i - j + 1;
            }
        }
        throw new RuntimeException("未找到匹配项！！！");
    }


}
